<template>
  <el-dialog
    :custom-class="'notice-send-dialog' + ((selfFiles.length > 0 && ' no-content') || '')"
    :visible="visible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :show-close="false"
    top="5vh"
    left="10vw"
    center="">
    <div v-if="selfFiles.length === 0" class="notice-editor" ref="tinyEditor">
      <tinymce-editor v-model="editContent" v-if="tinyMcHeight" :height="tinyMcHeight" use-in-report></tinymce-editor>
    </div>
    <div class="extra-info">
      <el-row type="flex" align="middle">
        <el-col :span="12" v-if="orgName">
          <span class="label">发送单位：</span>
          {{ orgName }}
        </el-col>
        <el-col :span="12" style="text-align: right" v-if="showTimeLimit">
          <span class="label" :class="{ warning: showLimitWarning }">整改期限：</span>
          <el-date-picker
            :popper-append-to-body="false"
            v-model="deadline"
            type="date"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd 23:59"
            format="yyyy-M-d"
            placeholder="选择日期"
            :editable="false"
            prefix-icon="el-icon-date"
            @change="dateChange"></el-date-picker>
        </el-col>
      </el-row>
      <el-row v-if="showSelfUpload" class="upload-file-row" type="flex" align="middle">
        <span class="label">使用已有通知书：</span>
        <upload-file
          class="upload-cmpt"
          :fileList="selfFiles"
          :max-limit="1"
          accept=".pdf,.doc,.docx,.wps"
          accept-inline
          @change="onWindowResize"></upload-file>
      </el-row>
      <el-alert
        v-if="selfFiles.length"
        class="self-tips"
        title="将使用已有通知书发送给该单位！"
        type="warning"
        :closable="false"></el-alert>
      <slot name="footer"></slot>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button class="footer-btn" plain @click="closeDialog">取 消</el-button>
      <el-button class="footer-btn" type="primary" @click="sendMessage">{{ confirmLabel }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import TinymceEditor from '@com/TinymceEditor.vue'
import { formatDate } from '@utility/utility'
import UploadFile from './UploadFile.vue'

export default {
  components: { TinymceEditor, UploadFile },
  props: {
    visible: {
      type: Boolean,
    },
    content: {
      type: String,
    },
    orgName: {
      type: String,
    },
    currTime: {
      type: String,
    },
    minTime: {
      type: String,
      default: formatDate(new Date(), 'yyyy-MM-dd hh:mm'),
    },
    maxTime: {
      type: String,
    },
    showTimeLimit: {
      type: Boolean,
      default: true,
    },
    showSelfUpload: {
      type: Boolean,
      default: true,
    },
    confirmLabel: {
      type: String,
      default: '发送通知',
    },
  },
  data() {
    return {
      pickerOptions: {
        disabledDate: time => {
          let minInValid = false
          let maxInValid = false
          const dayItem = formatDate(time, 'yyyyMMdd235959') // 格式化到当天结束时刻
          if (this.minTime) {
            minInValid = dayItem < formatDate(this.minTime, 'yyyyMMddhhmmss')
          }
          if (this.maxTime) {
            maxInValid = dayItem > formatDate(this.maxTime, 'yyyyMMddhhmmss')
          }
          return minInValid || maxInValid
        },
      },
      tinyMcHeight: 0,
      editContent: '',
      deadline: '',
      resetTimer: null,
      showLimitWarning: false,
      selfFiles: [],
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.selfFiles = []
        this.$nextTick(() => {
          this.tinyMcHeight = this.$refs.tinyEditor.clientHeight || 350
          // 重置内容
          this.editContent = this.content
          this.deadline = this.currTime + ' 23:59'
        })
        window.addEventListener('resize', this.onWindowResize)
      } else {
        this.tinyMcHeight = 0
        window.removeEventListener('resize', this.onWindowResize)
      }
    },
    content: {
      immediate: true,
      handler() {
        console.log('watch...content...')
        this.editContent = this.content
      },
    },
    currTime: {
      immediate: true,
      handler() {
        this.deadline = this.currTime + ' 23:59'
      },
    },
  },
  methods: {
    closeDialog() {
      this.$emit('update:visible', false)
    },
    dateChange(e) {
      this.$nextTick(() => {
        if (e) {
          const limitDate = formatDate(e, 'yyyy年M月d日')
          this.editContent = this.editContent.replace(
            /<span class="limit">\d+年\d+月\d+日<\/span>/,
            `<span class="limit">${limitDate}</span>`
          )
        }
      })
    },
    getEditorDateLimitEl() {
      const editorIframe = this.$el.querySelector('iframe')
      if (editorIframe) {
        const editorDocument = editorIframe.contentWindow.document
        const limitElement = editorDocument.querySelector('span.limit')
        return limitElement
      }
    },
    // 发送通知
    sendMessage() {
      if (!this.showTimeLimit) {
        this.$emit('submit', this.editContent)
        return
      }
      if (!this.deadline) {
        this.$message({
          message: '请选择日期',
          type: 'warning',
        })
        return
      }
      // 校验整改通知书中的日期和选中的日期是否一致
      const limitElement = this.getEditorDateLimitEl()
      if (limitElement) {
        const dateStr = limitElement.innerText
        if (formatDate(this.deadline, 'yyyy年M月d日') !== dateStr) {
          this.$message.warning('请确保整改期限数据一致！')
          limitElement.style.color = 'red'
          this.showLimitWarning = true
          this.resetTimer = setTimeout(() => {
            this.dateChange(this.deadline)
            this.showLimitWarning = false
          }, 2500)
          return
        }
      }

      if (!this.editContent.trim().length === 0) {
        this.$message({
          message: '请输入内容',
          type: 'warning',
        })
        return
      }
      this.$emit('submit', this.editContent, this.deadline, this.selfFiles)
    },
    onWindowResize() {
      this.tinyMcHeight = 0
      this.$nextTick(() => {
        this.tinyMcHeight = (this.$refs.tinyEditor && this.$refs.tinyEditor.clientHeight) || 350
      })
    },
  },
  beforeDestroy() {
    if (this.resetTimer) {
      clearTimeout(this.resetTimer)
    }
    window.removeEventListener('resize', this.onWindowResize)
  },
}
</script>

<style lang="scss" scoped>
.notice-send-dialog {
  ::v-deep &.el-dialog {
    // height: 80%;
    height: 85%;
    display: flex;
    flex-direction: column;
    width: 23cm;
    &.no-content {
      height: 400px;
    }
    .el-dialog__body {
      padding-bottom: 10px;
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }
    .notice-editor {
      flex: 1;
      width: 21cm !important;
      margin: auto;
      overflow: hidden;
    }

    .extra-info {
      margin-top: 20px;
      font-size: 16px;
      padding: 0 20px;
      .label {
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }
      .el-icon-date {
        line-height: 43px;
      }
      .el-input__inner {
        padding-left: 35px;
      }

      .warning {
        color: #f02525;
      }
      .upload-file-row {
        align-items: flex-start;
        margin-top: 10px;
        .upload-cmpt {
          flex: 1;
        }
      }
      .self-tips {
        margin-top: 20px;
      }
    }
    .dialog-footer {
      display: flex;
      justify-content: center;
      .footer-btn {
        min-width: 100px;
        height: 38px;
        margin: 0 20px;
      }
    }
  }
}
</style>
